package cn.yfj.org.service.impl;

import cn.yfj.basic.service.impl.BaseServiceImpl;
import cn.yfj.org.domain.Department;
import cn.yfj.org.mapper.DepartmentMapper;
import cn.yfj.org.service.IDepartmentServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service //交给spring管理
public class DepartmentServiceImplService extends BaseServiceImpl<Department> implements IDepartmentServiceI {
    @Autowired //依赖注入
    private DepartmentMapper departmentMapper;
    @Override
    public void save(Department department) {
        departmentMapper.save(department);
        this.update(department);//抽qu
    }
    @Transactional //修改提交事务
    @Override
    public void update(Department department) {
        //这里不仅需要保存数据，还需要保存ditPath 后期用来做上级部门回显
        String dirPath = "";
        if(department.getParent() == null){
            //1.如果新增的是定顶级 直接保存自己的自增id  /自己的id
            dirPath = "/"+department.getId();
        }else{
            //2.如果不是顶级  找出父亲的ditPath + /自己的id
            Department parent = departmentMapper.loadById(department.getParent().getId());
            dirPath = parent.getDirPath() + "/"+department.getId();
        }
        System.out.println(dirPath);
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    @Override
    public List<Department> queryTree() {

        List<Department> allDepts = departmentMapper.loadAll();
        //下面内层嵌套循环，查询父亲把所有数据，抽成map<部门ID，部门对象>
        HashMap<Long, Department> allDeptMap = new HashMap<>();
        for (Department tmp : allDepts) {
            allDeptMap.put(tmp.getId(),tmp);
        }

        List<Department> firstDepts = new ArrayList<>();
        for (Department deptTmp : allDepts) {
            if(deptTmp.getParent_id() == null){//代表是顶级
            //  从所有数据中找出第一层级 firstDepartment   我们需要返回的数据
                firstDepts.add(deptTmp);
            }else{
            //     只要不是第一层级的，找自己的上级，并将自己放入上级的children中
                Department parent = allDeptMap.get(deptTmp.getParent_id());
                if(parent != null){
                    parent.getChildren().add(deptTmp);
                }
            }
        }
        return firstDepts;
    }

}
